defmodule EliPhxPlay.Context.GroupMembers do

  @moduledoc """
  群关系模块
  负责处理群关系相关的逻辑
  """
  import Ecto.Query, warn: false
  alias EliPhxPlay.Repo
  alias EliPhxPlay.ChatSchema.GroupMembers
  alias EliPhxPlay.ChatSchema.Groups

  @doc"""
  创建群关系并且role为owner
  """
  def create_group_member(group_id, user_id) do
    %GroupMembers{}
    |> GroupMembers.changeset(%{group_id: group_id, user_id: user_id, role: "owner"})
    |> Repo.insert()
  end

  @doc """
  创建群关系role为默认值不用写
  """
  def create_group_member_role_member(group_id, user_id) do

    case user_in_group?(group_id, user_id) do
      true -> {:error, "用户已经是群成员"}
      false ->
        %GroupMembers{}
        |> GroupMembers.changeset(%{group_id: group_id, user_id: user_id})
        |> Repo.insert()
    end
  end


  @doc """
  检查用户是否已经是群成员
  """
  def user_in_group?(group_id, user_id) do
    GroupMembers
    |> where([gm], gm.group_id == ^group_id and gm.user_id == ^user_id)
    |> Repo.exists?()
  end


  @doc """
  获取用户在哪些群中
  """
  def get_user_groups(user_id) do
    from(gm in GroupMembers,
      join: g in Groups, on: gm.group_id == g.group_id,
      where: gm.user_id == ^user_id,
      select: %{
        #群关系信息
        member_id: gm.member_id,
        group_id: g.group_id,
        user_id: gm.user_id,
        role: gm.role,
        group_nickname: gm.group_nickname,
        is_muted: gm.is_muted,
        mute_until: gm.mute_until,
        #群信息
        group_name: g.group_name,
        group_avatar: g.group_avatar,
        group_description: g.group_description,
        group_code: g.group_code
      }
    )
    |> Repo.all()
  end


end
